const express = require('express')
const cors = require('cors')
const helmet = require('helmet')
const rateLimit = require('express-rate-limit')
const config = require('./config')
const responseFormatter = require('./middleware/responseFormatter')

// 路由导入
const authRoutes = require('./routes/auth')
const userRoutes = require('./routes/user')
const novelRoutes = require('./routes/novels')
const chapterRoutes = require('./routes/chapters')
const paymentRoutes = require('./routes/payment')

const app = express()

// 安全中间件
app.use(helmet())

// 跨域设置
app.use(
  cors({
    origin: [
      'http://localhost:3000',
      'http://localhost:5173',
      'http://localhost:5174',
      'http://192.168.1.103:3000',
      'http://192.168.1.103:5173',
      'http://192.168.1.103:5174'
    ],
    credentials: true
  })
)

// 限流 - 开发环境下放宽限制
const limiter = rateLimit({
  windowMs: 1 * 60 * 1000, // 1分钟
  max: 60, // 限制每个IP 1分钟内最多60个请求
  message: {
    success: false,
    message: '请求过于频繁，请稍后再试',
    code: 'TOO_MANY_REQUESTS'
  },
  standardHeaders: true,
  legacyHeaders: false,
  skip: req => {
    // 开发环境下跳过限流
    return process.env.NODE_ENV === 'development'
  }
})
app.use(limiter)

// 解析JSON
app.use(express.json({ limit: '10mb' }))
app.use(express.urlencoded({ extended: true }))

// 响应格式化中间件
app.use(responseFormatter)

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    success: true,
    message: 'Novel Platform API is running',
    timestamp: new Date().toISOString()
  })
})

// API路由
app.use('/api/auth', authRoutes)
app.use('/api/users', userRoutes)
app.use('/api/novels', novelRoutes)
app.use('/api/chapters', chapterRoutes)
app.use('/api/payment', paymentRoutes)

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: 'API endpoint not found'
  })
})

// 全局错误处理
app.use((error, req, res, next) => {
  console.error('Global error:', error)

  res.status(error.status || 500).json({
    success: false,
    message: error.message || '服务器内部错误',
    ...(config.server.env === 'development' && { stack: error.stack })
  })
})

module.exports = app
